#include "medicalrecordwidget.h"
#include "ui_medicalrecordwidget.h"
#include "../../network/networkclient.h"
#include <QMessageBox>
#include <QDateTime>

MedicalRecordWidget::MedicalRecordWidget(const Doctor& doctor, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MedicalRecordWidget),
    m_doctor(doctor),
    m_hasPatient(false) {
    ui->setupUi(this);
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &MedicalRecordWidget::onMessageReceived);
}

MedicalRecordWidget::MedicalRecordWidget(const Doctor& doctor, const Patient& patient, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MedicalRecordWidget),
    m_doctor(doctor),
    m_hasPatient(true) {
    ui->setupUi(this);
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &MedicalRecordWidget::onMessageReceived);
    
    setupPatientInfo(patient);
}

MedicalRecordWidget::MedicalRecordWidget(const Doctor& doctor, const Patient& patient, int appointmentId, const QDateTime& appointmentTime, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MedicalRecordWidget),
    m_doctor(doctor),
    m_hasPatient(true),
    m_appointmentId(appointmentId),
    m_appointmentTime(appointmentTime) {
    ui->setupUi(this);
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &MedicalRecordWidget::onMessageReceived);
    
    setupPatientInfo(patient);
}

void MedicalRecordWidget::setupPatientInfo(const Patient& patient) {
    // 自动填充患者ID
    ui->patientIdEdit->setText(QString::number(patient.id));
    ui->patientIdEdit->setReadOnly(true);
    
    // 显示患者基本信息（如果UI中有相关字段）
    setWindowTitle(QString("为患者 %1 创建病历").arg(patient.realName));
}

MedicalRecordWidget::~MedicalRecordWidget() {
    delete ui;
}

void MedicalRecordWidget::on_saveButton_clicked() {
    if (ui->patientIdEdit->text().isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入患者ID");
        return;
    }
    
    // 如果有预约时间，检查当前时间是否已到预约时间
    qDebug() << "预约时间是否有效:" << m_appointmentTime.isValid();
    qDebug() << "预约时间:" << m_appointmentTime.toString("yyyy-MM-dd HH:mm:ss");
    
    if (m_appointmentTime.isValid()) {
        QDateTime currentTime = QDateTime::currentDateTime();
        qDebug() << "当前时间:" << currentTime.toString("yyyy-MM-dd HH:mm:ss");
        qDebug() << "比较结果 (current < appointment):" << (currentTime < m_appointmentTime);
        
        if (currentTime < m_appointmentTime) {
            QMessageBox::warning(this, "提示", 
                QString("当前时间尚未到预约时间，无法创建病历！\n"
                       "预约时间：%1\n"
                       "当前时间：%2")
                .arg(m_appointmentTime.toString("yyyy-MM-dd HH:mm"))
                .arg(currentTime.toString("yyyy-MM-dd HH:mm")));
            return;
        }
    } else {
        qDebug() << "预约时间无效，跳过时间验证";
    }
    
    MedicalRecord record;
    record.patientId = ui->patientIdEdit->text().toInt();
    record.doctorId = m_doctor.id;
    record.appointmentId = m_appointmentId;  // 设置预约ID
    record.visitTime = QDateTime::currentDateTime();
    record.chiefComplaint = ui->chiefComplaintEdit->toPlainText();
    record.presentIllness = ui->presentIllnessEdit->toPlainText();
    record.physicalExam = ui->physicalExamEdit->toPlainText();
    record.diagnosis = ui->diagnosisEdit->text();
    record.treatment = ui->treatmentEdit->toPlainText();
    record.notes = ui->notesEdit->toPlainText();
    
    QJsonObject request = record.toJson();
    NetworkClient::instance().sendRequest(MSG_CREATE_MEDICAL_RECORD, request);
}

void MedicalRecordWidget::on_clearButton_clicked() {
    ui->patientIdEdit->clear();
    ui->chiefComplaintEdit->clear();
    ui->presentIllnessEdit->clear();
    ui->physicalExamEdit->clear();
    ui->diagnosisEdit->clear();
    ui->treatmentEdit->clear();
    ui->notesEdit->clear();
}

void MedicalRecordWidget::on_backButton_clicked() {
    // 如果是从患者详情页进入的，发送返回信号
    if (m_hasPatient) {
        emit backToPatientDetail();
    }
}

void MedicalRecordWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_CREATE_MEDICAL_RECORD_RESPONSE) {
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", "病历创建成功");
            on_clearButton_clicked();
            emit recordCreated();  // 发送病历创建成功信号
        } else {
            QMessageBox::warning(this, "失败", data["error"].toString());
        }
    }
}

